<?php
	$data = array();
	$cus = '';
	$account = array();
	$products = array();
	$address = array();
	$billing_address = array();
	$shipping_method = '';
	$comment = '';
	$method = '';
	$region = '';
	$send_confirmation = 1;
	$currency = 'USD';
	
	if($data = $this->getRequest()->getPost()){		
		//var_dump($data);
		foreach($data as $key => $value){
			//var_dump($key);
			//var_dump($value);
			if($key == 'customer_id'){
				$cus = $value;
			}elseif ($key == 'billing_address'){
				$billing_address = $value;
			}elseif ($key == 'shipping_method'){
				$shipping_method = $value;
			}elseif ($key == 'comment'){
				$comment = $value;
			}elseif ($key == 'payment'){
				$method = $value;
				//var_dump($method['method']);
			}elseif ($key == 'products'){
				$products = $value;
			}elseif ($key == 'region'){
				$region = $value;
			}
		}		
		// // load customer		
		// $customer = Mage::getModel('customer/customer')->load($cus);
		// $account['group_id'] =  $customer['group_id'];
		// $account['email'] =  $customer['email'];
			
		//billing
		$firstname = '';
		$lastname = '';
		$company = '';
		$street = array() ;
		$city = '';
		$postcode = '';
		$country_id ='';		
		$telephone ='';
		$fax = '';
		
		foreach($billing_address as $key=>$value){			
			if($key == 'firstname'){
				$firstname =$value ;
			}elseif( $key == 'lastname' ){
				$lastname =$value ;
			}elseif( $key == 'company' ){
				$company =$value ;
			}elseif( $key == 'street' ){
				$street =$value ;
			}elseif( $key == 'city' ){
				$city =$value ;
			}elseif( $key == 'postcode' ){
				$postcode =$value ;
			}elseif( $key == 'country_id' ){
				$country_id =$value ;
			}elseif( $key == 'telephone' ){
				$telephone =$value ;
			}elseif( $key == 'fax' ){
				$fax =$value ;
			}
		}
		if($firstname == ''){
			$billing_address = array("customer_address_id"=>'',"prefix"=>"", "firstname"=>"n/a","middlename"=>"","lastname"=>"n/a","suffix"=>"","company"=>"n/a","street"=>array("n/a","n/a"), "city"=> "n/a","country_id"=>"SG","region"=>"n/a","postcode"=> "n/a","telephone"=>  "123456","fax"=>  "123456", "vat_id"=>  "");
		} else {
			$billing_address = array("customer_address_id"=>'',"prefix"=>"", "firstname"=>$firstname,"middlename"=>"","lastname"=>$lastname,"suffix"=>"","company"=>$company,"street"=>$street, "city"=> $city,"country_id"=>$country_id,"region"=>$region,"postcode"=> $postcode,"telephone"=>  $telephone,"fax"=>  $fax, "vat_id"=>  "");
		}		
		//var_dump($billing_address);
		
		//$id=1; // get Customer Id
		$customer = Mage::getModel('customer/customer')->load($cus);

		$transaction = Mage::getModel('core/resource_transaction');
		$storeId = $customer->getStoreId();
		$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

		$order = Mage::getModel('sales/order')
		->setIncrementId($reservedOrderId)
		->setStoreId($storeId)
		->setQuoteId(0)
		->setGlobal_currency_code('USD')
		->setBase_currency_code('USD')
		->setStore_currency_code('USD')
		->setOrder_currency_code('USD');

		// set Customer data
		$order->setCustomer_email($customer->getEmail())
		->setCustomerFirstname($customer->getFirstname())
		->setCustomerLastname($customer->getLastname())
		->setCustomerGroupId($customer->getGroupId())
		->setCustomer_is_guest(0)
		->setCustomer($customer);

		// set Billing Address
		$billing = $customer->getDefaultBillingAddress();
		$billingAddress = Mage::getModel('sales/order_address')
		->setStoreId($storeId)
		->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
		->setCustomerId($customer->getId())
		->setCustomerAddressId($customer->getDefaultBilling())
		->setCustomer_address_id($billing->getEntityId())
		->setPrefix($billing->getPrefix())
		->setFirstname($billing->getFirstname())
		->setMiddlename($billing->getMiddlename())
		->setLastname($billing->getLastname())
		->setSuffix($billing->getSuffix())
		->setCompany($billing->getCompany())
		->setStreet($billing->getStreet())
		->setCity($billing->getCity())
		->setCountry_id($billing->getCountryId())
		->setRegion($billing->getRegion())
		->setRegion_id($billing->getRegionId())
		->setPostcode($billing->getPostcode())
		->setTelephone($billing->getTelephone())
		->setFax($billing->getFax());
		$order->setBillingAddress($billingAddress);

		$shipping = $customer->getDefaultShippingAddress();
		$shippingAddress = Mage::getModel('sales/order_address')
		->setStoreId($storeId)
		->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
		->setCustomerId($customer->getId())
		->setCustomerAddressId($customer->getDefaultShipping())
		->setCustomer_address_id($shipping->getEntityId())
		->setPrefix($shipping->getPrefix())
		->setFirstname($shipping->getFirstname())
		->setMiddlename($shipping->getMiddlename())
		->setLastname($shipping->getLastname())
		->setSuffix($shipping->getSuffix())
		->setCompany($shipping->getCompany())
		->setStreet($shipping->getStreet())
		->setCity($shipping->getCity())
		->setCountry_id($shipping->getCountryId())
		->setRegion($shipping->getRegion())
		->setRegion_id($shipping->getRegionId())
		->setPostcode($shipping->getPostcode())
		->setTelephone($shipping->getTelephone())
		->setFax($shipping->getFax());

		$order->setShippingAddress($shippingAddress)
		->setShipping_method('flatrate_flatrate')
		->setShippingDescription($this->getCarrierName('flatrate'));

		$orderPayment = Mage::getModel('sales/order_payment')
		->setStoreId($storeId)
		->setCustomerPaymentId(0)
		->setMethod('purchaseorder')
		->setPo_number(' - ');
		$order->setPayment($orderPayment);

		// let say, we have 2 products
		$subTotal = 0;
		// $products = array(
			// '1001' => array(
			// 'qty' => 1
			// ),
			// '1002' ->array(
			// 'qty' => 3
			// ),
		// );
		foreach ($products as $productId=>$product) {
		$_product = Mage::getModel('catalog/product')->load($productId);
		$rowTotal = $_product->getPrice() * $product['qty'];
		$orderItem = Mage::getModel('sales/order_item')
		->setStoreId($storeId)
		->setQuoteItemId(0)
		->setQuoteParentItemId(NULL)
		->setProductId($productId)
		->setProductType($_product->getTypeId())
		->setQtyBackordered(NULL)
		->setTotalQtyOrdered($product['qty'])
		->setQtyOrdered($product['qty'])
		->setName($_product->getName())
		->setSku($_product->getSku())
		->setPrice($_product->getPrice())
		->setBasePrice($_product->getPrice())
		->setOriginalPrice($_product->getPrice())
		->setRowTotal($rowTotal)
		->setBaseRowTotal($rowTotal);

		$subTotal += $rowTotal;
		$order->addItem($orderItem);
		}

		$order->setSubtotal($subTotal)
		->setBaseSubtotal($subTotal)
		->setGrandTotal($subTotal)
		->setBaseGrandTotal($subTotal);

		$transaction->addObject($order);
		$transaction->addCommitCallback(array($order, 'place'));
		$transaction->addCommitCallback(array($order, 'save'));
		$transaction->save();
		
		$resource = Mage::getSingleton('core/resource');
		$readConnection = $resource->getConnection('core_read');
		$query2 = 'SELECT MAX(entity_id) from sales_flat_order where customer_id = '.$cus;
		$new_record = $readConnection->fetchOne($query2);
		$new_id = (int)$new_record;
		$user = Mage::getSingleton('admin/session');
		$userId = $user->getUser()->getUserId();
	
	$linkprint = $this->getUrl('')."pos/index/index";
?>

<button class="print">print</button>

<form action="http://gobblershop.com/magento/index.php/admin/pos_order/index/" method="POST" name="form_order" enctype="multipart/form-data">
	<input type="hidden" value="<?php echo $new_id?>" name="order_id">	
	<button class="print">cancel order</button>
</form>
<?php // $_order = Mage::getModel('sales/order')->load($new_record) ?>

<?php $_helper = $this->helper('catalog/output');?>
<?php $_order = Mage::getModel('sales/order')->load($new_id) ?>
<?php  //var_dump($_order['total_item_count']);  ?>

<div class="receipt" style="width:207px; padding: 10px; border: 1px solid; font-size: 10px;min-height:100%; margin: 0 auto;">
    <div class="logo" style="text-align: center;">
        <img src="<?php echo $this->getSkinUrl('images/logo.png') ?>" width="205px" alt="<?php echo $this->getLogoAlt() ?>" />
    </div>
    <div class="store-info" style="text-align: center; overflow: hidden;clear:both">
        <table width="100%" align="center">
            <tbody><tr>
                <td>
                    Maple Tree House
                </td>
            </tr>
             <tr>
                <td>
                     Maple Tree House
                </td>
            </tr>
             <tr>
                <td>
                   Address
                </td>
            </tr>
             <tr>
                <td>
                  Phone
                </td>
            </tr>
             <tr>
                <td>
                    Email
                </td>
            </tr>
             <tr>
                <td>
                    <?php echo $this->getUrl('')?>
                </td>
            </tr>
        </tbody></table>        
    </div>
    <div class="title" style="overflow: hidden; margin-bottom: 10px;">
        <table width="100%">
            <tbody><tr>
                <td align="center" style="text-transform: uppercase; font-size: 12px; font-weight: bold;">
                    Retail Receipt
                </td>
            </tr>
            <tr>
                <td>
                    Avaiable in day
                </td>
            </tr>
        </tbody></table>        
    </div>
    <div class="content" style="">
        <div class="staff-info" style="border-bottom: 1px dashed; ">
            <table width="100%">
                <tbody><tr>
                    <td align="left">
                        NO: <?php echo $_order['created_at']?>
                    </td>
                    <td align="center">
                        DATE: <?php echo $_order['created_at']?>
                    </td>                    
                </tr>              
            </tbody></table>
            <table width="100%">               
                <tbody><tr>                   
                    <td align="right">
                        Receipt: <?php echo $_order['increment_id']?>
                    </td>
                </tr>
            </tbody></table>
        </div>
        <div class="order-info" style="border-bottom: 1px dashed; ">
            <table width="100%">
				<tbody>
				<?php $_items = $_order->getItemsCollection(); ?>
				<?php $_count = $_items->count(); ?>
				<?php foreach ($_items as $_item): ?>
					<?php $product = Mage::getModel('catalog/product')->load($_item['product_id']);
						//var_dump($product);
					?>
					<tr>
						<td colspan="2">
							<?php echo $product['barcode'];?>							
						</td>
						<td colspan="2" align="right">
							<?php echo $_item->getName();?>
						</td>
					</tr>
					<tr>						
						 <td>
							<?php echo (int)$_item->getQtyOrdered();?>
						</td>
						 <td>
							x<?php echo $_item->getPrice();?>
						</td>
						 <td align="right">
							<?php 
								 $tierprice1 = $product['tier_price'];
								 $rowTotal1 = '';	
								// var_dump($_item);
								if(count($tierprice1)>0){									
									foreach($tierprice1 as $temp){
										//var_dump($temp);
										if($temp['price_qty'] == $_item->getQtyOrdered()){
											$rowTotal1 =  $temp['price'];
											break;
										}else {
											$rowTotal1 = $product->getPrice() * $_item->getQtyOrdered();
										}
									}
								}else {
									echo 'asda';
									$rowTotal1 = $_item->getPrice() * $_item->getQtyOrdered();
								}	
							?>							
							<?php echo $rowTotal1 ;//$_item->getPrice()*$_item->getQtyOrdered();?>
						</td>
					</tr>     
				<?php endforeach; ?>        
				</tbody>
			</table>
        </div>
        <div class="order-total">
            <table width="100%">               
                <tbody><tr>
                    <td align="right">
                        Total amount
                    </td>
                    <td>:</td>
                    <td align="right">
                        <?php echo $_order['grand_total']?>
                    </td>
                </tr>
                <tr>
                    <td align="right">
                        Qty
                    </td>
                    <td>:</td>
                    <td align="right">
                       <?php echo $_order['total_item_count']?>
                    </td>
                </tr>
            </tbody></table>
        </div>
        <div class="payment-method" style="margin-top: 10px;">
            <table width="100%">
                <tbody>
					<tr>
						<td>Payment Method:</td>
						<td><?php echo $_order->getPayment()->getMethodInstance()->getTitle()?></td>
					</tr>										
				</tbody>
			</table>                           
            <table width="100%">
                <tbody>
				<tr>
                	<td>Scanner no :</td>                    
                	<td><?php echo Mage::getSingleton('core/session')->getAdminPrint()?></td>
                </tr>				
            </tbody></table>
        </div>
        <div class="customer-info" style="margin-top: 5px;">
            <span style="text-transform: uppercase; text-decoration: underline;">Customer infomation</span>
            <table>
                <tbody><tr>
                	<td>Code</td>
                    <td>:</td>
                	
					<?php $customer_data = Mage::getModel('customer/customer')->load($_order['customer_id']); ?>
					<td><?php echo $customer_data['read_id'] ?></td>
                </tr>
                <tr>
                	<td>Name</td>
                    <td>:</td>
                	<td><?php echo $_order['customer_lastname']?></td>
              </tr>
            </tbody></table>
        </div>
        <div style="margin: 0 auto; width: 50%; border-top: 1px dashed; text-align: center; margin-top: 10px;">
            <table width="100%">
                <tbody><tr>
                    <td>
                        Thank you!
                    </td>
                </tr>
                <tr>
                    <td>
                        See you again!
                    </td>
                </tr>
            </tbody></table>
        </div>
    </div>
</div>
<script type="text/javascript">decorateTable('my-orders-table', {'tbody' : ['odd', 'even'], 'tbody tr' : ['first', 'last']})</script>
<script type="text/javascript">
	jQuery(".print").click(function() {
		printElem({pageTitle:'Gobbler shop'});
	}); 
	function printElem(options){
		jQuery('.receipt').printElement(options);
	};
</script>
<?php }?>